package cn.yuanqiao.system.service.impl;


import cn.yuanqiao.archive.appManager.domain.TenantRyMjDzb;
import cn.yuanqiao.archive.appManager.domain.YqSy;
import cn.yuanqiao.archive.appManager.service.ITenantMijiComparisonTableService;
import cn.yuanqiao.archive.appManager.service.IYqSyService;
import cn.yuanqiao.archive.utils.FileWaterMark;

import cn.yuanqiao.common.core.context.ResponseUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.file.FileUploadUtils;
import cn.yuanqiao.system.domain.YqCyxz;
import cn.yuanqiao.system.mapper.YqCyxzMapper;
import cn.yuanqiao.system.service.ISysConfigService;
import cn.yuanqiao.system.service.IYqCyxzService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 常用下载Service业务层处理
 *
 * @author sy
 * @date 2023-09-14
 */
@Service
public class YqCyxzServiceImpl implements IYqCyxzService
{
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private YqCyxzMapper yqCyxzMapper;
    @Autowired
    private IYqSyService yqSyService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Value("${FBswitch}")
    private Boolean FBswitch;
    @Autowired
    private ITenantMijiComparisonTableService archiveReleaseService;

    /**
     * 查询常用下载
     *
     * @param ID 常用下载主键
     * @return 常用下载
     */
    @Override
    public YqCyxz selectYqCyxzByID(Long ID)
    {
        return yqCyxzMapper.selectYqCyxzByID(ID);
    }

    /**
     * 查询常用下载列表
     *
     * @param yqCyxz 常用下载
     * @return 常用下载
     */
    @Override
//    public List<YqCyxz> selectYqCyxzList(String tableName,Long userId,Long deptId)
    public List<YqCyxz> selectYqCyxzList(YqCyxz yqCyxz)
    {
        if(FBswitch){
            List<TenantRyMjDzb> getdamjbyrymj = archiveReleaseService.getdamjbyrymj();
            yqCyxz.setMj(" and MJ in ('" + getdamjbyrymj.stream().map(m->m.getDaMj()).collect(Collectors.joining("','")) +"') ");
        }
        return yqCyxzMapper.selectYqCyxzList(yqCyxz);
    }

    /**
     * 新增常用下载
     *
     * @param yqCyxz 常用下载
     * @return 结果
     */
    @Override
    public int insertYqCyxz(YqCyxz yqCyxz)
    {
        yqCyxz.setCreateTime(DateUtils.getNowDate());
        return yqCyxzMapper.insertYqCyxz(yqCyxz);
    }

    /**
     * 上传文件
     *
     * @param file 常用下载
     * @return 结果
     */
    @Override
    public int upload(MultipartFile file, String mj) {
        LoginUser user = SecurityUtils.getLoginUser();

        if (user == null) {
            user = new LoginUser();
            user.setUserId(1L);
        }

        String uploadPath = sysConfigService.selectConfigByKey("YQ_MNT");
        if (StringUtils.isEmpty(uploadPath)) {
            throw new ServiceException("系统参数错误YQ_MNT未找到配置！");
        }
        String maxSize = sysConfigService.selectConfigByKey("DA_FILE_MAX");
        String extensions = sysConfigService.selectConfigByKey("DA_ALLOWED_EXTENSION");
        FileUploadUtils.setDefaultConfig(maxSize, extensions);
        if (file.getSize()>= FileUploadUtils.DEFAULT_MAX_SIZE){
            throw new ServiceException("上传文件过大！");
        }
        Date nowDate = new Date();
        String filePath = String.valueOf(nowDate.getTime());
        uploadPath = uploadPath + "upload/" + filePath;
        String absPath;
        File file1;
        try {
            // 创建上传路径文件夹如果不存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            // 保存文件  http://127.0.0.1:8080/profile/6090083/2024/08/05/神通标准库卷内件_20240805104810A002.xlsx

            file1 = new File(uploadPath+"/"+file.getOriginalFilename());
            file.transferTo( Paths.get(uploadPath+"/"+file.getOriginalFilename()));
            //absPath = FileUploadUtils.upload(uploadPath, file);
            //absPath= absPath.substring(absPath.lastIndexOf("profile")+15);
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            throw new ServiceException("文件上传失败！");
        }
        YqCyxz yqCyxz = new YqCyxz();
        yqCyxz.setFileName(file.getOriginalFilename());
        yqCyxz.setFilePath(file1.getAbsolutePath());
        yqCyxz.setFileSize(String.valueOf(file.getSize()));
        yqCyxz.setReleaseScope(user.getSysUser().getDeptId().toString());
        yqCyxz.setUploaderId(user.getUserId());
        yqCyxz.setUploaderName(user.getUsername());
        yqCyxz.setCreatorId(user.getUserId());
        yqCyxz.setCreateTime(nowDate);
        yqCyxz.setMj(mj);
        return yqCyxzMapper.upload(yqCyxz);

    }

    /**
     * 修改常用下载
     *
     * @param yqCyxz 常用下载
     * @return 结果
     */
    @Override
    public int updateYqCyxz(YqCyxz yqCyxz)
    {
        return yqCyxzMapper.updateYqCyxz(yqCyxz);
    }

    /**
     * 发布文件
     *
     * @param yqCyxz 常用下载
     * @return 结果
     */
    @Override
    public int release(YqCyxz yqCyxz)
    {
        yqCyxz.setLastupdateTime(DateUtils.getNowDate());
        return yqCyxzMapper.release(yqCyxz);
    }

    /**
     * 取消发布
     *
     * @param yqCyxz 常用下载
     * @return 结果
     */
    @Override
    public int disRelease(YqCyxz yqCyxz)
    {
        return yqCyxzMapper.disRelease(yqCyxz);
    }

    /**
     * 批量删除常用下载
     *
     * @param IDs 需要删除的常用下载主键
     * @return 结果
     */
    @Override
    public int deleteYqCyxzByIDs(Long[] IDs)
    {
        YqCyxz yqCyxz = new YqCyxz();
        int num = 0;
        List<YqCyxz> yqCyxzList = yqCyxzMapper.selectYqCyxzByIDs(yqCyxz.getTableName(),IDs);
        num = yqCyxzMapper.deleteYqCyxzByIDs(yqCyxz.getTableName(),IDs);
        if (num>0){
            for(YqCyxz entity:yqCyxzList){
                String filePath=entity.getFilePath();
                File f = new File(filePath);
                if(f.exists() && f.isFile()) {
                    f.delete();
                }
            }
        }
        return num;
    }

    @Override
    public void download(Long[] IDs,String sydm, HttpServletResponse response) throws Exception{
//        ServletOutputStream out = null;
//        FileInputStream fis = null;
        YqCyxz yqCyxz = new YqCyxz();
        List<YqCyxz> yqCyxzList = yqCyxzMapper.selectYqCyxzByIDs(yqCyxz.getTableName(),IDs);
        for(YqCyxz entity:yqCyxzList){
            String filePath=entity.getFilePath();
            File f = new File(filePath);
            if (!f.exists()) {
                throw new ServiceException("文件不存在!");
            }

            if (StringUtils.isNotEmpty(sydm)){
                //添加水印
                YqSy yqSy = new YqSy();
                yqSy.setSydm(sydm);
                yqSy = yqSyService.selectYqSyBySydm(yqSy);
                if (null!=yqSy&&StringUtils.isNotEmpty(yqSy.getSynr())){
                    String fpath = f.getPath();
                    String fileFullName = fpath.substring(fpath.lastIndexOf("\\")+1,fpath.lastIndexOf("."));
                    String prefix=fpath.substring(fpath.lastIndexOf(".")+1);
                    String 	waterMarkFilepath = sysConfigService.selectConfigByKey("WATERMARKFILEPATH");
                    //生成水印文件地址
                    if(!StringUtils.isEmpty(waterMarkFilepath)) {
                        File folder = new File(waterMarkFilepath);
                        if (!folder.exists()) {
                            if (folder.mkdirs()) {

                            }else {
                                throw new RuntimeException("路径"+waterMarkFilepath+"不存在！");
                            }
                        }
                        waterMarkFilepath+=fileFullName+"."+prefix;
                    }else {
                        throw new RuntimeException("没有在系统参数表配置添加水印文件保存路径WATERMARKFILEPATH字段");
                    }
                    if("pdf".equals(prefix.toLowerCase())) {
                        FileWaterMark.pdfWaterMark(fpath,waterMarkFilepath,yqSy);
                        f = new File(waterMarkFilepath);
                    } else if ("png".equals(prefix.toLowerCase())||"jpg".equals(prefix.toLowerCase())||"jpeg".equals(prefix.toLowerCase())
                            ||"tif".equals(prefix.toLowerCase())||"tiff".equals(prefix.toLowerCase())) {
                        FileWaterMark.addPictureWaterMark(fpath,waterMarkFilepath,yqSy);
                        f = new File(waterMarkFilepath);
                    }
                }
            }

            BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
            byte[] buf = new byte[1024];
            boolean isOnLine=false;
            int len = 0;
            response.reset(); // 非常重要
            ResponseUtils.defaultResponse(response);
            String  fileName= entity.getFileName();

            if (isOnLine) { // 在线打开方式
                URL u = new URL("file:///" + filePath);
                response.setContentType(u.openConnection().getContentType());
                response.setHeader("Content-Disposition", "inline; filename=" + fileName);
                // 文件名应该编码成UTF-8
            } else { // 纯下载方式
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=" + new Date().getTime()+fileName.substring(fileName.lastIndexOf(".")));
            }
            OutputStream out = response.getOutputStream();
            while ((len = br.read(buf)) > 0){
                out.write(buf, 0, len);
            }
            br.close();
            out.close();
        }

    }

//    @Override
//    public void download(Long[] IDs, HttpServletResponse response) throws Exception {
//
//        YqCyxz yqCyxz = new YqCyxz();
//
//        for(YqCyxz entity: yqCyxzMapper.selectYqCyxzByIDs(yqCyxz.getTableName(),IDs)) {
//
//            String filePath = entity.getFilePath();
//            File file = new File(filePath);
//
//            if(!file.exists()) {
//                throw new ServiceException("文件不存在");
//            }
//
//            response.reset();
//            response.setContentType("application/octet-stream");
//            response.addHeader("Content-Disposition", "attachment;filename="+
//                    URLEncoder.encode(entity.getFileName()));
//
//            try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
//                BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
//
//                byte[] buff = new byte[1024];
//                int len;
//                while((len=bis.read(buff))!=-1) {
//                    bos.write(buff, 0, len);
//                }
//            }
//
//        }
//
//    }

    /**
     * 删除常用下载信息
     *
     * @param ID 常用下载主键
     * @return 结果
     */
    @Override
    public int deleteYqCyxzByID(Long ID)
    {
        return yqCyxzMapper.deleteYqCyxzByID(ID);
    }
}
